class Auth {
    constructor() {
        console.log('Auth 构造函数执行');
        this.token = localStorage.getItem('token');
        this.user = null;
        
        // 从localStorage获取用户信息
        const userJson = localStorage.getItem('user');
        if (userJson) {
            try {
                this.user = JSON.parse(userJson);
                console.log('从localStorage获取到用户信息:', this.user);
            } catch (e) {
                console.error('解析用户信息失败:', e);
                localStorage.removeItem('user');
            }
        }
        
        // 初始化DOM元素
        this.loginModal = document.getElementById('loginModal');
        this.registerModal = document.getElementById('registerModal');
        this.loginForm = document.getElementById('loginForm');
        this.registerForm = document.getElementById('registerForm');
        this.authButtons = document.getElementById('authButtons');
        this.userMenu = document.getElementById('userMenu');
        this.userAvatar = document.getElementById('userAvatar');
        this.userNickname = document.getElementById('userNickname');
        
        this.init();
    }
    
    init() {
        console.log('初始化Auth模块...');
        // 检查登录状态
        this.updateUIByAuthStatus();
        
        // 注册事件监听
        this.registerEventListeners();
        
        // 初始化头像预览
        this.initAvatarPreview();
    }
    
    initAvatarPreview() {
        const avatarInput = document.getElementById('registerAvatar');
        const avatarPreview = document.getElementById('avatarPreview');
        
        if (avatarInput && avatarPreview) {
            avatarInput.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        avatarPreview.src = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
    }
    
    updateUIByAuthStatus() {
        console.log('更新UI状态，用户信息:', this.user);
        if (this.token && this.user) {
            // 已登录状态
            if (this.authButtons) this.authButtons.style.display = 'none';
            if (this.userMenu) {
                this.userMenu.style.display = 'flex';
                if (this.userAvatar) {
                    // 确保头像路径正确
                    let avatarPath = this.user.avatar || '/images/default-avatar.png';
                    
                    // 处理头像路径
                    if (avatarPath && avatarPath.startsWith('/uploads/') && !avatarPath.startsWith('/uploads/avatars/')) {
                        // 如果是旧路径格式，修正为新路径格式
                        const filename = avatarPath.split('/').pop();
                        avatarPath = `/uploads/avatars/${filename}`;
                    }
                    
                    this.userAvatar.src = avatarPath;
                }
                if (this.userNickname) {
                    console.log('设置用户昵称:', this.user.nickname);
                    this.userNickname.textContent = this.user.nickname || '未知用户';
                }
            }
        } else {
            // 未登录状态
            if (this.authButtons) this.authButtons.style.display = 'flex';
            if (this.userMenu) this.userMenu.style.display = 'none';
        }
    }
    
    registerEventListeners() {
        // 登录表单提交
        if (this.loginForm) {
            this.loginForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleLogin();
            });
        }
        
        // 注册表单提交
        if (this.registerForm) {
            this.registerForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.handleRegister();
            });
        }
    }
    
    async handleLogin() {
        const email = document.getElementById('loginEmail').value;
        const password = document.getElementById('loginPassword').value;
        
        try {
            console.log('开始登录请求...');
            const response = await fetch('/api/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ email, password })
            });
            
            const data = await response.json();
            console.log('登录响应数据:', data);
            
            if (response.ok) {
                console.log('登录成功，用户信息:', data.user);
                this.setAuth(data.token, data.user);
                this.closeLoginModal();
                
                // 登录成功后立即更新UI
                this.updateUIByAuthStatus();
                
                alert('登录成功');
                
                // 刷新页面以确保所有组件都能获取到最新的登录状态
                window.location.reload();
            } else {
                alert(data.error || '登录失败');
            }
        } catch (error) {
            console.error('登录错误:', error);
            alert('登录失败，请稍后重试');
        }
    }
    
    async handleRegister() {
        // 获取表单数据
        const nickname = document.getElementById('registerNickname').value;
        const email = document.getElementById('registerEmail').value;
        const password = document.getElementById('registerPassword').value;
        const confirmPassword = document.getElementById('registerConfirmPassword').value;
        const captcha = document.getElementById('registerCaptcha').value;
        const avatarInput = document.getElementById('registerAvatar');
        
        // 验证表单
        if (password !== confirmPassword) {
            alert('两次输入的密码不一致');
            return;
        }
        
        // 创建FormData对象用于上传文件
        const formData = new FormData();
        formData.append('nickname', nickname);
        formData.append('email', email);
        formData.append('password', password);
        formData.append('captcha', captcha);
        
        // 如果上传了头像，添加到表单数据
        if (avatarInput && avatarInput.files.length > 0) {
            formData.append('avatar', avatarInput.files[0]);
        }
        
        try {
            const response = await fetch('/api/auth/register', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (response.ok) {
                alert('注册成功');
                this.closeRegisterModal();
                this.showLoginModal();
                // 重置表单
                document.getElementById('registerForm').reset();
                const avatarPreview = document.getElementById('avatarPreview');
                if (avatarPreview) {
                    avatarPreview.src = '/images/default-avatar.png';
                }
            } else {
                alert(data.error || '注册失败');
                this.refreshCaptcha();
            }
        } catch (error) {
            console.error('注册错误:', error);
            alert('注册失败，请稍后重试');
            this.refreshCaptcha();
        }
    }
    
    setAuth(token, user) {
        console.log('设置用户认证信息:', { token, user });
        this.token = token;
        this.user = user;
        localStorage.setItem('token', token);
        localStorage.setItem('user', JSON.stringify(user));
        
        // 立即更新UI
        this.updateUIByAuthStatus();
    }
    
    clearAuth() {
        this.token = null;
        this.user = null;
        localStorage.removeItem('token');
        localStorage.removeItem('user');
    }
    
    async logout() {
        try {
            if (this.token) {
                // 调用后端登出接口
                await fetch('/api/auth/logout', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${this.token}`
                    }
                });
            }
        } catch (error) {
            console.error('登出错误:', error);
        } finally {
            // 不管后端是否成功，前端都清除登录状态
            this.clearAuth();
            this.updateUIByAuthStatus();
            alert('已退出登录');
            
            // 如果在需要登录的页面，则返回首页
            const requiresAuth = ['/profile', '/upload'];
            if (requiresAuth.some(path => window.location.pathname.startsWith(path))) {
                window.location.href = '/';
            }
        }
    }
    
    showLoginModal() {
        if (this.loginModal) {
            this.loginModal.style.display = 'block';
            document.body.style.overflow = 'hidden';
        }
    }
    
    closeLoginModal() {
        if (this.loginModal) {
            this.loginModal.style.display = 'none';
            document.body.style.overflow = 'auto';
            if (this.loginForm) this.loginForm.reset();
        }
    }
    
    showRegisterModal() {
        if (this.registerModal) {
            this.registerModal.style.display = 'block';
            document.body.style.overflow = 'hidden';
            this.refreshCaptcha();
        }
    }
    
    closeRegisterModal() {
        if (this.registerModal) {
            this.registerModal.style.display = 'none';
            document.body.style.overflow = 'auto';
            if (this.registerForm) this.registerForm.reset();
            const avatarPreview = document.getElementById('avatarPreview');
            if (avatarPreview) {
                avatarPreview.src = '/images/default-avatar.png';
            }
        }
    }
    
    refreshCaptcha() {
        const captchaImage = document.getElementById('captchaImage');
        if (captchaImage) {
            captchaImage.src = `/api/captcha?t=${new Date().getTime()}`;
        }
    }
}

// 全局函数用于模态框控制
function showLoginModal() {
    authInstance.showLoginModal();
}

function closeLoginModal() {
    authInstance.closeLoginModal();
}

function showRegisterModal() {
    authInstance.showRegisterModal();
}

function closeRegisterModal() {
    authInstance.closeRegisterModal();
}

function refreshCaptcha() {
    authInstance.refreshCaptcha();
}

function logout() {
    authInstance.logout();
}

// 初始化Auth实例
const authInstance = new Auth(); 